package com.imooc.course.thrift;

import com.imooc.thrift.user.UserService;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.layered.TFramedTransport;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author LiJian
 * @date 2022/10/25
 */
@Component
public class ServiceProvider {
    @Value("${thrift.user.ip}")
    private String serverIp;
    @Value("${thrift.user.port}")
    private int serverPort;

    private enum ServiceType{
        USER,
        MESSAGE
    }
    public UserService.Client getUserService() {
        return getService(serverIp,serverPort,ServiceType.USER);
    }

    private <T> T getService(String ip,int port,ServiceType serviceType){
        try {
            TSocket socket = new TSocket(ip,port,10000);
            TTransport transport = new TFramedTransport(socket);
            transport.open();
            TProtocol protocol = new TBinaryProtocol(transport);
            TServiceClient client = null ;
            switch (serviceType){
                case USER:
                    client =new UserService.Client(protocol);
                    break;
                default:
                    break;
            }
            return (T)client;
        }catch (TTransportException e){
            e.printStackTrace();
            return null;
        }
    }
}
